package com.ltg.framework.util.pdf;
import com.itextpdf.awt.geom.Rectangle2D;
import com.itextpdf.text.*;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.parser.ImageRenderInfo;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.RenderListener;
import com.itextpdf.text.pdf.parser.TextRenderInfo;
import com.ltg.framework.util.ImageUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author：邹祥发
 * @date：2022/11/24 10:19
 * @description：PDF工具类，提供 水印、签名、盖章 功能
 */
@Slf4j
public class PdfUtil1 {

    /**
     * 往PDF上添加文字水印
     *
     * @param inputFile     原文件
     * @param outputFile    加水印后的文件
     * @param waterMarkName 水印字符
     */
    public static void addWaterMark(String inputFile, String outputFile, String waterMarkName) {
        PdfReader reader = null;
        PdfStamper stamper = null;
        try {
            reader = new PdfReader(inputFile);
            stamper = new PdfStamper(reader, Files.newOutputStream(Paths.get(outputFile)));
            //水印字体，放到服务器上对应文件夹下（arial中文不生效）
            //BaseFont base = BaseFont.createFont("D:/workspace/springboot/src/main/resources/arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
            Rectangle pageRect;
            PdfGState gs = new PdfGState();
            //填充不透明度  为1完全不透明
            gs.setFillOpacity(0.1f);
            //笔画不透明度， 为1完全不透明
            gs.setStrokeOpacity(0.1f);
            int total = reader.getNumberOfPages() + 1;
            JLabel label = new JLabel();
            FontMetrics metrics;
            int textH;
            int textW;
            label.setText(waterMarkName);
            metrics = label.getFontMetrics(label.getFont());
            textH = metrics.getHeight();
            textW = metrics.stringWidth(label.getText());
            PdfContentByte under;
            int interval = 0;
            for (int i = 1; i < total; i++) {
                pageRect = reader.getPageSizeWithRotation(i);
                //在字体下方加水印
                under = stamper.getOverContent(i);
                under.beginText();
                under.saveState();
                under.setGState(gs);
                //这里修改水印字体大小
                under.setFontAndSize(base, 36);
                //这里设置字体上下间隔
                for (int height = interval + textH; height < pageRect.getHeight(); height = height + textH * 9) {
                    //这里设置字体左右间隔
                    for (int width = interval + textW; width < pageRect.getWidth() + textW; width = width + textW * 4) {
                        //这里设置倾斜角度
                        under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW, height - textH, 45);
                    }
                }
                under.endText();
            }
            stamper.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (stamper != null) {
                    stamper.close();
                }
            } catch (IOException | DocumentException e) {
                e.printStackTrace();
            }
            if (reader != null) {
                reader.close();
            }
        }
    }



    /**
     * pdf插入图片
     *
     * @param oldPath 插入图片前的路径
     * @param newPath 插入图片后的路径
     * @param imgPath 图片路径
     * @throws IOException
     * @throws DocumentException
     */
    public static void addImage(String oldPath, String newPath, String imgPath) throws IOException, DocumentException {
        InputStream inputStream = Files.newInputStream(Paths.get(oldPath));
        FileOutputStream out = new FileOutputStream(newPath);
        PdfReader reader = new PdfReader(inputStream);
        //pdf页数
        int pdfPages = reader.getNumberOfPages();
        PdfStamper stamper = new PdfStamper(reader, out);
        //图片
        BufferedImage bufferedImage = ImageIO.read(Files.newInputStream(Paths.get(imgPath)));
        //x轴坐标
        int x = 350;
        //y轴坐标
        int y = 20;
        //图片放置的页码
        for (int i = pdfPages; i <= pdfPages; i++) {
            //图片处理
            Image img = Image.getInstance(ImageUtil.imageToBytes((bufferedImage), "png"));
            //设置图片大小
            img.scaleAbsolute(192, 100);
            img.setTransparency(new int[0]);
            //设置图片位置
            img.setAbsolutePosition(x, y);
            stamper.getOverContent(i).addImage(img);
        }
        //关闭资源
        stamper.close();
        out.close();
        reader.close();
    }
}
